package org.geektimes.projects.user.web.listener;

import org.eclipse.microprofile.config.ConfigValue;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.geektimes.context.ComponentContext;
import org.geektimes.projects.jmx.UserManager;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.sql.DBConnectionManager;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.logging.Logger;

/**
 * 测试用途
 */
@Deprecated
public class TestingListener implements ServletContextListener {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            exportMBean();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    private void testGetApplicationName(ServletContext servletContext) {
        ConfigProviderResolver configProviderResolver = getConfigProviderResolver(servletContext.getClassLoader());
        if (configProviderResolver != null) {
            String applicationName = configProviderResolver.getConfig().getValue("application.name", String.class);
            logger.info("application.name = " + applicationName);
            Integer applicationPort = configProviderResolver.getConfig().getValue("application.port", Integer.class);
            logger.info("application.port = " + applicationPort);
        }
    }

    private ConfigProviderResolver getConfigProviderResolver(ClassLoader classLoader) {
        ServiceLoader<ConfigProviderResolver> serviceLoader = ServiceLoader.load(ConfigProviderResolver.class, classLoader);
        Iterator<ConfigProviderResolver> iterator = serviceLoader.iterator();
        if (iterator.hasNext()) {
            return iterator.next();
        }
        return null;
    }

    private void exportMBean() throws Exception {
        // 获取平台 MBean Server
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // 为 UserMXBean 定义 ObjectName
        ObjectName objectName = new ObjectName("org.geektimes.projects.user.management:type=User");
        // 创建 UserMBean 实例
        User user = new User();
        mBeanServer.registerMBean(createUserMBean(user), objectName);
    }

    private static Object createUserMBean(User user) throws Exception {
        return new UserManager(user);
    }
}
